package com.buybuyyi.stylistcrm.resource.controllers.img;

import com.alibaba.fastjson.JSONObject;
import com.buybuyyi.stylistcrm.resource.controllers.DefaultController;
import com.buybuyyi.stylistcrm.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import stylistcrm.core.services.order.enums.EnumExceptionCode;
import stylistcrm.core.services.order.exception.BizException;
import stylistcrm.core.services.resource.ObjectResourceService;

import java.io.InputStream;
import java.util.UUID;

/**
 * Created by cheny on 2016/10/27.
 * 图片处理接口
 */
@Controller
@RequestMapping("/file")
public class ImgController extends DefaultController{

    @Autowired
    private ObjectResourceService objectResourceService;

    @ResponseBody
    @RequestMapping("/uploadimage")
    public JSONObject uploadImage(@RequestParam("file") MultipartFile file) throws BizException{
        Long userId=super.checkLogin();
        String fileName=file.getOriginalFilename();
        InputStream stream;
        try {
            stream = file.getInputStream();
            String uuid= UUID.randomUUID().toString();
            String newFileName="";
            if(StringUtil.isNotBlank(fileName)&&fileName.contains(".")){
                newFileName=uuid+fileName.substring(fileName.lastIndexOf(".")+1);
            }
            String fileUrl=objectResourceService.preSave(stream, fileName, newFileName, uuid, "", userId);
            JSONObject result=new JSONObject();
            result.put("url",fileUrl);
            result.put("fileName",fileName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(EnumExceptionCode.EC0006);
        }
    }
}
